package net.forty2ware.vintagesofa

class HttpHelper {
  static final String ENCODING = 'UTF-8'

  private String doMethod(map) {
    StringBuilder data = new StringBuilder()
    if (map.dataMap) {
      def firstData = true
      map.dataMap.each { key, value ->
        if (!firstData) { data.append('&') }
        data.append(URLEncoder.encode(key.toString(), ENCODING)).append('=').append(URLEncoder.encode(value.toString(), ENCODING))
        firstData = false
      }
    }


    // println map.urlString
    def url = new URL(map.urlString)

    def connection = url.openConnection()
    connection.doInput = true
    connection.useCaches = false
    connection.setRequestMethod(map.method)
    
    def writer = null
    if (map.dataMap || map.content) {
      connection.doOutput = true
      connection.setRequestProperty('Content-Type', map.mimeType)
      writer = new OutputStreamWriter(connection.outputStream)
      writer.write(data.toString())
      writer.write(map.content)
      writer.flush()
    } else { 
      connection.doOutput = false
    }


    def inputStream
    try {
      inputStream = connection.inputStream
    } catch (IOException e) {
      inputStream = connection.errorStream
    }

    if (!inputStream) { throw new RuntimeException("no server response") }

    def result = new StringBuilder()
    def reader = new BufferedReader(new InputStreamReader(inputStream))

    reader.eachLine { line ->
      result.append(line)
    }

    if (writer) { writer.close() }
    reader.close()

    return result.toString()
  }

  String post(urlString, dataMap, mimeType, content) {
    doMethod(
      'method'    :'GET',
      'urlString' :urlString,
      'dataMap'   :dataMap,
      'mimeType'  :mimeType,
      'content'   :content,
    )
  }

  String get(urlString) {
    doMethod(
      'method'    :'GET',
      'urlString' :urlString, 
    )
  }

  String put(urlString) {
    doMethod(
      'method'    :'PUT',
      'urlString' :urlString, 
    )
  }

  String delete(urlString) {
    doMethod(
      'method'    :'DELETE',
      'urlString' :urlString, 
    )
  }

}
